import React from "react";
import { createForm } from "@formily/core";
import { createSchemaField, ISchema } from "@formily/react";
import { getOptions } from "src/utils";

import {
  Form,
  FormItem,
  Input,
  Select,
  Submit,
  FormGrid,
  FormProps,
} from "@formily/antd";
import { OwnerSelect } from "../OwnersSelect";
import FetchSelect from "../FetchSelect";

interface Props {
  type: string;
  onAutoSubmit: (values: any) => any;
}

const SearchForm: React.FC<Props> = (props) => {
  const form = createForm();
  const SchemaField = createSchemaField({
    components: {
      FormItem,
      Input,
      Select,
      OwnerSelect,
      FetchSelect,
      FormGrid,
      Submit,
    },
  });

  const formProps: FormProps = {
    form,
    onAutoSubmit: props.onAutoSubmit,
  };

  const schema: ISchema = {
    type: "object",
    properties: {
      formGrid: {
        type: "void",
        "x-decorator": "FormItem",
        "x-component": "FormGrid",
        "x-component-props": {
          minColumns: 4,
          columnGap: 20,
        },
        properties: {
          query: {
            type: "string",
            title: "Query",
            "x-decorator": "FormItem",
            "x-component": "Input",
          },
          owner: {
            type: "string",
            title: "Owner",
            "x-decorator": "FormItem",
            "x-component": "OwnerSelect",
          },
          storageUri: {
            type: "string",
            title: "Storage",
            "x-decorator": "FormItem",
            "x-component": "FetchSelect",
            "x-component-props": {
              style: { width: 230 },
            },
            "x-reactions": (field) => {
              field.display = props.type === "entity" ? "visible" : "none";
            },
          },
          type: {
            type: "string",
            title: "Type",
            "x-decorator": "FormItem",
            "x-component": "Select",
            enum: getOptions([
              ["MySQL", "mysql"],
              ["Redis", "redis"],
              ["MongoDB", "mongodb"],
            ]),
            "x-reactions": (field) => {
              field.display = props.type === "storage" ? "visible" : "none";
            },
          },
          submit: {
            type: "void",
            "x-decorator": "FormItem",
            "x-component": "Submit",
            "x-content": "提交",
          },
        },
      },
    },
  };
  return (
    <Form {...formProps}>
      <SchemaField schema={schema} />
    </Form>
  );
};

export default SearchForm;
